import React, { useState } from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { observer } from 'mobx-react-lite';
import {
  Appbar,
  Card,
  Text,
  TextInput,
  Button,
  Chip,
  Switch,
  Divider,
  useTheme,
  HelperText,
} from 'react-native-paper';
import { FuelType, ExpenseType } from '../../types';
import { FuelFormData, FormProps } from './types';

export const FuelFormPage = observer(
  ({ initialData, onSubmit, onCancel }: FormProps<FuelFormData>) => {
    const theme = useTheme();
    const [formData, setFormData] = useState<FuelFormData>({
      type: ExpenseType.FUEL,
      amount: 0,
      date: new Date().toISOString().split('T')[0],
      fuelType: FuelType.GASOLINE_92,
      fuelAmount: 0,
      fuelPrice: 0,
      isFullTank: false,
      isLowFuel: false,
      ...initialData,
    });

    const [errors, setErrors] = useState<
      Partial<Record<keyof FuelFormData, string>>
    >({});

    const updateFormData = (field: keyof FuelFormData, value: any) => {
      setFormData(prev => ({
        ...prev,
        [field]: value,
      }));
      // 清除错误
      if (errors[field]) {
        setErrors(prev => ({
          ...prev,
          [field]: undefined,
        }));
      }
    };

    const validateForm = (): boolean => {
      const newErrors: Partial<Record<keyof FuelFormData, string>> = {};

      if (!formData.amount || formData.amount <= 0) {
        newErrors.amount = '请输入有效金额';
      }
      if (!formData.date) {
        newErrors.date = '请选择日期';
      }
      if (!formData.fuelAmount || formData.fuelAmount <= 0) {
        newErrors.fuelAmount = '请输入加油升数';
      }
      if (!formData.fuelPrice || formData.fuelPrice <= 0) {
        newErrors.fuelPrice = '请输入油价';
      }

      setErrors(newErrors);
      return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = () => {
      if (validateForm()) {
        onSubmit(formData);
      }
    };

    const fuelTypes = Object.values(FuelType);

    return (
      <SafeAreaView style={styles.container}>
        <Appbar.Header>
          <Appbar.BackAction onPress={onCancel} />
          <Appbar.Content title="加油记录" />
          <Appbar.Action icon="content-save" onPress={handleSubmit} />
        </Appbar.Header>

        <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
          {/* 油类型选择 */}
          <Card style={styles.card}>
            <Card.Content>
              <Text variant="titleMedium" style={styles.sectionTitle}>
                油类型
              </Text>
              <View style={styles.chipContainer}>
                {fuelTypes.map(type => (
                  <Chip
                    key={type}
                    selected={formData.fuelType === type}
                    onPress={() => updateFormData('fuelType', type)}
                    style={styles.chip}
                    textStyle={
                      formData.fuelType === type
                        ? styles.chipTextSelected
                        : styles.chipText
                    }
                  >
                    {type}
                  </Chip>
                ))}
              </View>
            </Card.Content>
          </Card>

          {/* 加油升数 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="加油升数 (L)"
                value={formData.fuelAmount.toString()}
                onChangeText={value =>
                  updateFormData('fuelAmount', parseFloat(value) || 0)
                }
                keyboardType="numeric"
                left={<TextInput.Icon icon="water" />}
                error={!!errors.fuelAmount}
                style={styles.input}
              />
              {errors.fuelAmount && (
                <HelperText type="error" visible={!!errors.fuelAmount}>
                  {errors.fuelAmount}
                </HelperText>
              )}
            </Card.Content>
          </Card>

          {/* 油价 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="油价 (¥/L)"
                value={formData.fuelPrice.toString()}
                onChangeText={value =>
                  updateFormData('fuelPrice', parseFloat(value) || 0)
                }
                keyboardType="numeric"
                left={<TextInput.Icon icon="pricetag" />}
                error={!!errors.fuelPrice}
                style={styles.input}
              />
              {errors.fuelPrice && (
                <HelperText type="error" visible={!!errors.fuelPrice}>
                  {errors.fuelPrice}
                </HelperText>
              )}
            </Card.Content>
          </Card>

          {/* 加油选项 */}
          <Card style={styles.card}>
            <Card.Content>
              <Text variant="titleMedium" style={styles.sectionTitle}>
                加油选项
              </Text>
              <View style={styles.switchContainer}>
                <Text variant="bodyMedium">加满油箱</Text>
                <Switch
                  value={formData.isFullTank}
                  onValueChange={value => updateFormData('isFullTank', value)}
                  color={theme.colors.primary}
                />
              </View>
              <Divider style={styles.divider} />
              <View style={styles.switchContainer}>
                <Text variant="bodyMedium">低油量提醒</Text>
                <Switch
                  value={formData.isLowFuel}
                  onValueChange={value => updateFormData('isLowFuel', value)}
                  color={theme.colors.tertiary}
                />
              </View>
            </Card.Content>
          </Card>

          {/* 金额输入 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="金额 (¥)"
                value={formData.amount.toString()}
                onChangeText={value =>
                  updateFormData('amount', parseFloat(value) || 0)
                }
                keyboardType="numeric"
                left={<TextInput.Icon icon="currency-cny" />}
                error={!!errors.amount}
                style={styles.input}
              />
              {errors.amount && (
                <HelperText type="error" visible={!!errors.amount}>
                  {errors.amount}
                </HelperText>
              )}
            </Card.Content>
          </Card>

          {/* 日期选择 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="日期"
                value={formData.date}
                onChangeText={value => updateFormData('date', value)}
                left={<TextInput.Icon icon="calendar" />}
                error={!!errors.date}
                style={styles.input}
              />
              {errors.date && (
                <HelperText type="error" visible={!!errors.date}>
                  {errors.date}
                </HelperText>
              )}
            </Card.Content>
          </Card>

          {/* 里程数 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="里程数 (km)"
                value={formData.mileage?.toString() || ''}
                onChangeText={value =>
                  updateFormData('mileage', parseInt(value) || 0)
                }
                keyboardType="numeric"
                left={<TextInput.Icon icon="speedometer" />}
                style={styles.input}
              />
            </Card.Content>
          </Card>

          {/* 地点 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="地点"
                value={formData.location || ''}
                onChangeText={value => updateFormData('location', value)}
                left={<TextInput.Icon icon="map-marker" />}
                style={styles.input}
              />
            </Card.Content>
          </Card>

          {/* 备注 */}
          <Card style={styles.card}>
            <Card.Content>
              <TextInput
                label="备注"
                value={formData.description || ''}
                onChangeText={value => updateFormData('description', value)}
                multiline
                numberOfLines={3}
                style={styles.input}
              />
            </Card.Content>
          </Card>

          {/* 提交按钮 */}
          <Button
            mode="contained"
            onPress={handleSubmit}
            style={styles.submitButton}
            contentStyle={styles.submitButtonContent}
          >
            保存记录
          </Button>
        </ScrollView>
      </SafeAreaView>
    );
  }
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    flex: 1,
    padding: 16,
  },
  formTypeCard: {
    marginBottom: 16,
  },
  formTypeContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  formTypeIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  formTypeIconText: {
    fontSize: 20,
  },
  formTypeText: {
    flex: 1,
  },
  card: {
    marginBottom: 16,
  },
  sectionTitle: {
    marginBottom: 12,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  chip: {
    marginBottom: 8,
  },
  chipText: {
    color: '#666',
  },
  chipTextSelected: {
    color: '#fff',
  },
  input: {
    marginBottom: 8,
  },
  switchContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
  },
  divider: {
    marginVertical: 8,
  },
  submitButton: {
    marginTop: 16,
    marginBottom: 32,
  },
  submitButtonContent: {
    paddingVertical: 8,
  },
});
